﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace KuaJing.Analysis
{
    public static class KMeansAnalyzer
    {  
        public static IEnumerable<TResult> KMeans<TSource,TResult>(this IEnumerable<TSource> source, Func<TSource, double> ySelector, int k, Func<Point,IEnumerable<TSource>, TResult> resultSelecto)
        {
            return KMeans(source, _ => k, ySelector,k, resultSelecto);
        }
        public static IEnumerable<TResult> KMeans<TSource,TResult>(this IEnumerable<TSource> source,Func<TSource, double> xSelector, Func<TSource, double> ySelector, int k, Func<Point, IEnumerable<TSource>, TResult> resultSelector)
        {
            var points = source.Select(s => new Point(
                  xSelector(s), ySelector(s))).ToArray();

            Point[] result;
            var asg = Clustering.KMeans(points, k, out result);
            return asg.Select((v, i) => new { Point = result[v], Source = source.ElementAt(i) })
                .GroupBy(r => r.Point).Select(ps => resultSelector(ps.Key, ps.Select(e => e.Source)));

        }

    }
}
